package com.deepglint.handler;

import com.deepglint.common.bo.ResultBean;
import com.deepglint.common.consts.Consts;
import com.deepglint.license.LicenseVerify;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc 证书校验拦截器
 *
 * @author huangchen@deepglint.com
 * 
 * @date 2019/3/14 13:09
 */
@Component
public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        LicenseVerify licenseVerify = new LicenseVerify();
        //校验证书是否有效
        boolean verifyResult = licenseVerify.verify();
        if(verifyResult){
            return true;
        }else{
            response.setCharacterEncoding(Consts.DEFAULT_ENCODING);
            response.setContentType(Consts.CONTENT_TYPE_APP_JSON);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            ObjectMapper mapper = new ObjectMapper();
            ResultBean resultBean = new ResultBean(ResultBean.FAIL, "您的证书无效，请核查服务器是否取得授权或重新申请证书！");
            response.getWriter().write(mapper.writeValueAsString(resultBean));
            return false;
        }
    }
}
